import React, { useEffect, useMemo, useState } from 'react'
import TrainItem from './TrainItem'
import { useLoaderData, useSearchParams } from 'react-router-dom'
import { getTrainListApi } from '../../../api/train'
import { Button, InfiniteScroll } from 'antd-mobile'
import dayjs from 'dayjs'
import styles from '../css/list.module.css'
function TrainList() {
    const {list}=useLoaderData()
    const [tarinList,setTrainList]=useState(list)
    const [page,setPage]=useState(2)
    const [sp,setSp]=useSearchParams()
    const spObj=useMemo(()=>Object.fromEntries(sp),[sp])
    const setDate=(num)=>{
        let now=dayjs(sp.get('date')).add(num,'day').format("YYYY-MM-DD")
        setSp({...spObj,date:now})
    }
    const [hasMore, setHasMore] = useState(true)
  async function loadMore() {
    const {data:list}=await getTrainListApi({...spObj,page})
    setTrainList(prev=>[...prev,...list])
    setPage(prev=>prev+1)
    if(list.length===0){
        setHasMore(false)
    }
  }
  useEffect(()=>{
    window.scrollTo({top:0})
    setTrainList(list)
    setPage(2)
    setHasMore(true)
  },[list])
  return (
    <div>
        <div className={styles.date}>
        <Button
          style={{ color: "#000" }}
          fill="none"
          size="mini"
          onClick={() => setDate(-1)}
          disabled={
           Math.ceil(dayjs(sp.get('date')).diff(dayjs(),'day',true))<=0
          }
        >
          前一天
        </Button>
        <span>{sp.get("date")}</span>
        <Button
          style={{ color: "#000" }}
          fill="none"
          size="mini"
          onClick={() => setDate(1)}
          disabled={
            Math.ceil(dayjs(sp.get("date")).diff(dayjs(), "day", true)) >= 4
          }
        >
          后一天
        </Button>
      </div>
        {
            tarinList.map((item,index)=>{
                return <TrainItem key={index} {...item}/>
            })
        }
       <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
    </div>
  )
}

export default TrainList
